from re import findall as find, search, split, sub as preg_replace, compile, match as matched
from pycube.core.urls.response import HttpResponse
from sys import exit
from pycube import simplejson



class url_parser:
    def __init__( self, request, set_header, set_code, rm_headers, template_engine, adv_tpl=None ):
        self.req = request
        self.requested_urls = []
        self.url = request.environ['REQUEST_URI']
        self.environ = request.environ
        self.config = request.config
        self.returned = []
        self.patterns = {}
        self.__remove_headers__ = rm_headers
        self.cur = ''
        self.finalize = False
        project_path = self.environ['PYCUBE_PROJECT']
        self.result_text = []
        self.set_header = set_header
        self.set_code = set_code

        self.iFoundSomeUrls = False

        #Checking for advanced template clones
        onceMatched = False
        if adv_tpl:
            for pattern, custom_config in adv_tpl:
                if matched( pattern, self.url ):
                    onceMatched = True
                    self.tpl = template_engine( self.req, project_path, self.config.DEBUG, custom_config )


        if not onceMatched:
            self.tpl = template_engine( self.req, project_path, self.config.DEBUG, self.config.TPL_CONF )

    def get( self, mask ): return True if search( compile( mask ), self.url ) else False

    def match( self, condition ):
        searching = search( condition, self.url )
        if searching:
            return searching
        else:
            return False

    def get_finalize_status( self ):
        return  self.finalize

    def response( self ):
        if not self.finalize:
            self.result_text.append( self.tpl.done() )

        return ''.join( self.result_text )


    def parser( self, args ):

        self.iFoundSomeUrls = True if self.url == '/' else False

        for pattern, module_path in args:
            if not self.finalize:
                searching = search( pattern , self.url )
                if searching:

                    self.iFoundSomeUrls = True if self.url != '/' else False

                    groups = searching.groups()
                    if type( module_path ).__name__ == "str":
                        mods = matched( "^(.*?)\.(\w{1,50})$", module_path )
                        if mods:

                            if len( groups ) > 0:
                                object = getattr( __import__( mods.group( 1 ), {}, {}, [''] ), mods.group( 2 ) )( self.req, self.tpl, *groups )
                                if object:
                                    self.recieve( object )
                            else:
                                object = getattr( __import__( mods.group( 1 ), {}, {}, [''] ), mods.group( 2 ) )( self.req, self.tpl )
                                if object:
                                   self.recieve( object )

                    else:
                        if callable( module_path ):
                            if len( groups ) > 0:
                                object = module_path( self.req, self.tpl, *groups )
                                if object:
                                    self.recieve( object )

                            else:
                                object = module_path( self.req, self.tpl )
                                if object:
                                    self.recieve( object )

        if not self.iFoundSomeUrls:
            if self.config.SYSTEM.has_key( 'USE_DEFAULT_404' ):
                if self.config.SYSTEM['USE_DEFAULT_404']:
                    self.set_code( 404 )
                    self.__remove_headers__()



    def recieve( self, object ):

        if not isinstance( object, dict ):
            self.result_text.append( str( object ) )
        else:
            for result_key, result_param in object.items():
                if result_key == 'redirect':
                    self.finalize = True
                    self.set_code( 302 )
                    self.set_header( 'Location', result_param )

                if result_key == 'html':
                    if 'json' not in object:
                        self.result_text.append( str( result_param ) )

                if result_key == 'finalize':
                    if result_param:
                        self.finalize = True

                if result_key == 'check_ajax':
                    if result_param:
                        if self.is_ajax():
                            self.finalize = True

                if result_key == 'json':
                    if result_param:
                        self.result_text.append( simplejson.dumps( result_param ) )

                if result_key == 'urls':

                    if result_param:
                        if isinstance( result_param, tuple ):
                            self.parser( result_param )



















